package com.tg.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.tg.exception.PermissionException;
import com.tg.pojo.User;
import com.tg.service.UserService;
import com.tg.utils.JwtUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotBlank;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/users")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;
    private String uploadImgName;
    private LineCaptcha lineCaptcha;

    @GetMapping
    public Result userInformation(@RequestHeader(name = "Authorization") String token) {
        String username = null;
        try {
            username = JwtUtils.parseToken(token);
        } catch (Exception e) {
            throw new PermissionException(Code.PERMISSION_ERR, e.getMessage(), e);
        }
        User user = userService.getByUsername(username);
        user.setPassword(null);
        return new Result(null, user, ResultMessage.GET_OK);
    }

    @GetMapping("/getUsers")
    public Result getUserByUsernames(String[] usernames) {
        return new Result(Code.GET_OK, userService.getUsers(usernames));
    }

    @GetMapping("/getCode")
    public void getCode(HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(90, 30, 4, 8);
        this.lineCaptcha = lineCaptcha;
        ServletOutputStream outputStream = response.getOutputStream();
        lineCaptcha.write(outputStream);
        outputStream.close();
    }

    @GetMapping("/add/{addFriendUsername}")
    public Result getFriendByUsername(@NotBlank(message = "查找用户名不得为空!") @PathVariable(required = false) String addFriendUsername) {
        User user = userService.getFriendByUsername(addFriendUsername);
        user.setPassword(null);
        return new Result(Code.GET_OK, user, ResultMessage.GET_OK);
    }

    @PostMapping("/register")
    public Result register(@RequestBody @Validated User user) throws IOException {
        if (!this.lineCaptcha.verify(user.getCode())) {
            return new Result(Code.REGISTER_ERR, null, ResultMessage.CODE_ERR);
        }
        user.setAvatar(uploadImgName);
        boolean flag = userService.register(user);
        Integer code = flag ? Code.REGISTER_OK : Code.REGISTER_ERR;
        String message = flag ? ResultMessage.REGISTER_OK : ResultMessage.REGISTER_EXITS;
        return new Result(code, null, message);
    }

    @PostMapping("/upload")
    public void upload(MultipartFile file) throws IOException {
        String baseDir = "D:/vueSpace/chat/src/assets/avatars";
        String originalFilename = file.getOriginalFilename();
        String path = UUID.randomUUID() + "-" + originalFilename;
        File uploadImg = new File(baseDir, path);
        if (!uploadImg.getParentFile().exists()) {
            uploadImg.getParentFile().mkdirs();
            file.transferTo(uploadImg.getAbsoluteFile());
        } else {
            file.transferTo(uploadImg.getAbsoluteFile());
        }
        this.uploadImgName = path;
    }

    @PostMapping("/login")
    public Result login(@RequestBody @Validated(User.Login.class) User user) {
        if (!this.lineCaptcha.verify(user.getCode())) {
            return new Result(Code.LOGIN_ERR, null, ResultMessage.CODE_ERR);
        }
        User userData = userService.login(user);
        boolean flag = Objects.nonNull(userData);
        if (flag) {
            String token = JwtUtils.createToken(user.getUsername());
//            ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
//            stringStringValueOperations.set(token,token);
            return new Result(Code.LOGIN_OK, token, ResultMessage.LOGIN_OK);
        }
        return new Result(Code.LOGIN_ERR, null, ResultMessage.LOGIN_ERR);
    }

}
